import UserStore from '../store/UserStore';
import {defaultConfig, setConfig} from '../utils/Notification';
import PushNotification, {Importance} from 'react-native-push-notification';
import {logger} from '../utils/util';
import navigator, {getNavigator} from '../utils/navigator';
import {getWorkAskTransportList} from '../net/seekOrder';
import backgroundTimePlugin from "../plugins/backgroundTimer";
let noticeId = '0';

/**
 * 初始化通知参数
 * @param {自定义参数} customerOptions 
 */
export const initConfig = (customerOptions = {}) => {
  const config = {
    ...defaultConfig,
    ...customerOptions,
  };
  setConfig(config);
};

/**
 * 唤起通知
 */
export const callNotification = () => {
  initConfig({
    onNotification: notification => {
      navigator.navigate('SeekOrder');
    },
  });
  PushNotification.localNotification({
    /* iOS and Android properties */
    id: noticeId,
    channelId: 'seek-order-0803', // (required) 填了channelId 通知才会有
    title: '快乐小熊猫', // (optional)
    message: '您有咨询工单等待处理，请前往处理', // (required)
    userInfo: {}, // (optional) default: {} (using null throws a JSON value '<null>' error)
    playSound: true, // (optional) 是否开启声音 default: true
    soundName: 'default', // (optional) 声音名称 Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
    vibrate: true, // 是否开启震动
    ticker: "您有咨询工单等待处理，请前往处理...", // (optional)
    priority: "max", // 优先级
  });
  UserStore.setValue('isSeekOrderTip', true)
};

// 获取未处理工单数量
export const getSeekOrderCount = () => {
  const {userInfo} = UserStore;
  let params = {
    cityId: userInfo && userInfo.deptId,
    disposeState: 0,
  };
  getWorkAskTransportList(params).then(res => {
    if (res.result && res.result.content && res.result.content.length) {
      UserStore.setValue('seekOrderCount', res.result.content.length);
      const _navigator = getNavigator()
      const isSeekOrderPage = _navigator.state.nav.routes.some(item => item.routeName == 'SeekOrder')
      !isSeekOrderPage && callNotification();
    } else {
      UserStore.setValue('seekOrderCount', 0);
    }
  });
};

// 定时器开关
export function triggerSeekOrderTimer (isOpen, time) {
  if (isOpen) {
    backgroundTimePlugin.setTimer({
      key: 'seekOrderInterval',
      type: 'interval',
      time: time || 60 * 1000,
      callback: () => {
        logger('[seekOrderTimer] time:', new Date().getTime())
        getSeekOrderCount();
      }
    })
  } else {
    backgroundTimePlugin.remove({key: 'seekOrderInterval', type: 'interval'})
  }
};

// 建立通知渠道
export function createChannel() {
  PushNotification.createChannel(
    {
      channelId: 'seek-order-0803', // (required)
      channelName: '咨询工单', // (required)
      channelDescription: '咨询工单通知渠道', // (optional) default: undefined.
      playSound: true, // (optional) default: true
      soundName: 'default', // (optional) See `soundName` parameter of `localNotification` function
      importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
      vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
    },
    created => logger(`createChannel returned '${created}'`), // (optional) callback returns whether the channel was created, false means it already existed.
  );
}

// 开启通知
export const startSeekOrderNotification = () => {
  createChannel();
  triggerSeekOrderTimer(true, 60 * 1000);
}

// 移除通知
export const removeNotification = () => {
  PushNotification.getDeliveredNotifications((identifiers) => {
    if (identifiers.some(item => item.identifier == 0)) {
      // 移除该通知
      PushNotification.removeDeliveredNotifications(['0']);
    }
  })
  UserStore.setValue('isSeekOrderTip', false)
}